﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Book_of_Shadow_Script.Scripts;

namespace Book_of_Shadow_Script
{
    public partial class Form1 : Form
    {
        Script scp;
        CodePage cdp;
        Stack<Int32> view_stk;
        public Form1()
        {
            InitializeComponent();
            Init();
            scp = new Script();
            cdp = new CodePage(0x20);
        }

        private void Init()
        {
            comboBox1.SelectedIndex = 0;
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            ScriptDetail sd=(ScriptDetail)scp.operation[listBox1.SelectedIndex];
            textBox1.Text = sd.DisplayByte();
            textBox2.Text = sd.DisplayText();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            scp.operation.Clear();
            listBox1.Items.Clear();
            SetOpenFileDialog("脚本文件(*.bin;*.obj)|*.bin;*.obj|所有文件|*.*");
            if (openFileDialog1.ShowDialog()==DialogResult.OK)
            {
                String fName=openFileDialog1.FileName;
                ScriptFormat sf;
                switch (listBox2.SelectedIndex)
                {
                    case 0: sf = ScriptFormat.BookOfShadows; break;
                    case 1: sf = ScriptFormat.Oreimou; break;
                    default: sf = ScriptFormat.Oreimou; break;
                }

                if (checkBox2.Checked)
                {
                    CustomEncoding en = new CustomEncoding(cdp.CharToByte(), cdp.ByteToChar());
                    scp.ReadFile(File.Open(fName, FileMode.Open, FileAccess.Read),sf, en);
                }
                else
                    scp.ReadFile(File.Open(fName, FileMode.Open, FileAccess.Read),sf);
            }
            foreach (ScriptDetail sd in scp.operation)
            {
                listBox1.Items.Add(sd.ToString());
            }
        }

        private void SetOpenFileDialog(string filter)
        {
            if (openFileDialog1==null) openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = filter;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.FilterIndex = 1;
        }

        private void button4_Click(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {
            SetSaveFileDialog("文本文件(*.txt)|*.txt|所有文件|*.*");
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                String fName = saveFileDialog1.FileName;
                StreamWriter sw = new StreamWriter(fName);
                scp.TextExport(sw);
                sw.Close();
            }
            System.Windows.Forms.MessageBox.Show("导出完成");
        }

        private void SetSaveFileDialog(string filter)
        {
            saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = filter;
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.FilterIndex = 1;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1 = new FolderBrowserDialog();
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                String dName = folderBrowserDialog1.SelectedPath;
                String[] Files = Directory.GetFiles(dName);
                foreach (String fName in Files)
                {
                    FileInfo fi = new FileInfo(fName);
                    if (fi.Extension != ".BIN" && fi.Extension != ".bin") continue;
                    if (fi.Name[0] != 'B') continue;
                    StreamWriter sw = new StreamWriter(fName + ".txt");
                    scp.operation.Clear();
                    scp.ReadFile(File.Open(fName, FileMode.Open, FileAccess.Read),ScriptFormat.BookOfShadows);
                    scp.TextExport(sw);
                    sw.Close();
                }
                System.Windows.Forms.MessageBox.Show("导出完成");
            }

        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button7_Click(object sender, EventArgs e)
        {
            SetOpenFileDialog("文本文件(*.txt)|*.txt|所有文件(*.*)|*.*");

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                String fName = openFileDialog1.FileName;
                AddFile(fName,GetTextFilterCurrent());
            }
            ShowCodePage();
        }

        private TextFilter GetTextFilterCurrent()
        {
            TextFilter tf = null;
            //System.Windows.Forms.MessageBox.Show(sr.CurrentEncoding.ToString());
            foreach (RadioButton rb in radiopanel.Controls)
            {
                if (rb.Checked)
                {
                    tf = TextFilter.GetFilter((FilterType)rb.TabIndex);
                }
            }
            return tf;
        }

        private void AddFile(String fName, TextFilter tf)
        {
            StreamReader sr = new StreamReader(fName);
            String str = "";
            Int32 line = 0;
            try
            {
                while (!sr.EndOfStream)
                {
                    bool control = false;
                    line++;
                    str = sr.ReadLine();

                    str = tf.filting(str);
                    for (int i = 0; i < str.Length; i++)
                    {
                        if (str[i] == '{') control = true;
                        if (str[i] == '}') control = false;
                        if (control) continue;
                        cdp.AddChar(str[i], checkBox1.Checked);
                    }
                }
            }
            catch (IllegalFormatException e)
            {
                MessageBox.Show("此行有格式错误：" + fName + line.ToString() + "  " + e.Message);
            }
            catch (Exception e)
            {
                MessageBox.Show("此行有非格式错误：" + fName + line.ToString() + "  " + e.Message);
            }
            sr.Close();
        }

        private void ShowCodePage()
        {
            listBox3.Items.Clear();
            foreach (String s2 in cdp.Output())
            {
                listBox3.Items.Add(s2);
            }
            label1.Text = String.Format("字符个数：{0:D}", listBox3.Items.Count);
            textBox5.Text = cdp.OutputIgnore();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            cdp.Clear(Convert.ToInt32(textBox4.Text,16));
            listBox3.Items.Clear();
            label1.Text = String.Format("字符个数：{0:D}", listBox3.Items.Count);
        }

        private void button9_Click(object sender, EventArgs e)
        {
            
            SetSaveFileDialog("码表文件(*.tbl)|*.tbl|所有文件|*.*");
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                String fName = saveFileDialog1.FileName;
                StreamWriter sw = new StreamWriter(fName,false,Encoding.Unicode);
                foreach (String s2 in cdp.Output())
                {
                    sw.WriteLine(s2);
                }
                sw.Close();
            }
            System.Windows.Forms.MessageBox.Show("导出完成");
        }

        private void button10_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1 = new FolderBrowserDialog();
            this.folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
            this.folderBrowserDialog1.SelectedPath = @"E:\game\test\text\导入文";
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                String dName = folderBrowserDialog1.SelectedPath;
                String[] Files = Directory.GetFiles(dName);
                foreach (String fName in Files)
                {
                    FileInfo fi = new FileInfo(fName);
                    TextFilter tf;
                    if (fi.Extension != ".TXT" && fi.Extension != ".txt") continue;
                    if (fi.Name[0]=='B' || fi.Name[0]=='b')
                        tf = TextFilter.GetFilter(FilterType.PointerAddress);
                    else
                        tf = TextFilter.GetFilter(FilterType.WQSGAddress);
                    AddFile(fName,tf);
                }
            }
            ShowCodePage();
        }

        private void button14_Click(object sender, EventArgs e)
        {
            CodePageFixed cpf = new CodePageFixed();
            SceneFileByte sf=null;
            if (!checkBoxUseCurrent.Checked)
            {
                cpf.Import(textBoxTableFile.Text);
            }
            if (textBoxTableFile.Enabled)
                sf = new SceneFileByte(textBoxSceneFile.Text,cpf);
            else
                switch (comboBox1.SelectedIndex)
                {
                    case 1:
                        sf = new SceneFileByte(textBoxSceneFile.Text, Encoding.Unicode);
                        break;
                    case 2:
                        sf = new SceneFileByte(textBoxSceneFile.Text, Encoding.UTF8);
                        break;
                    case 3:
                        sf = new SceneFileByte(textBoxSceneFile.Text, Encoding.GetEncoding(936));
                        break;
                    case 4:
                        sf = new SceneFileByte(textBoxSceneFile.Text, Encoding.GetEncoding(932));
                        break;
                }
            SceneFile st = null;
            if (radioButton4.Checked) st = new SceneFile_WQSG(textBoxSceneText.Text);
            if (radioButton6.Checked) st = new SceneFile_Book_of_Shadow(textBoxSceneText.Text);

            sf.Import(st);
            sf.Close();
            MessageBox.Show("导入完成");

        }

        private void checkBoxUseCurrent_CheckedChanged(object sender, EventArgs e)
        {
            textBoxTableFile.Enabled = !checkBoxUseCurrent.Checked;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            SetOpenFileDialog("码表文件(*.tbl,*.txt)|*.tbl;*.txt|所有文件|*.*");
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                textBoxTableFile.Text = openFileDialog1.FileName;
        }

        private void button12_Click(object sender, EventArgs e)
        {
            SetOpenFileDialog("脚本文件(*.bin)|*.bin|所有文件|*.*");
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                textBoxSceneFile.Text = openFileDialog1.FileName;
        }

        private void button13_Click(object sender, EventArgs e)
        {
            SetOpenFileDialog("文本文件(*.txt)|*.txt|所有文件(*.*)|*.*");
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                textBoxSceneText.Text = openFileDialog1.FileName;
        }

        private void button2_Click(object sender, EventArgs e)//文件夹导入
        {
            CodePageFixed cpf = new CodePageFixed();
            if (!checkBoxUseCurrent.Checked)//从码表文件中获得码表
            {
                cpf.Import(textBoxTableFile.Text);
            }


            String dName = textBoxSceneFile.Text;
            if (dName.Last()!='\\') dName+='\\';
            String dNameText = textBoxSceneText.Text;
            String[] Files = Directory.GetFiles(dName);
            String[] FilesText = Directory.GetFiles(dNameText);
            foreach (String fName in FilesText)
            {
                int ed=-1;
                FileInfo fi = new FileInfo(fName);
                SceneFile st = null;
                if (fi.Extension != ".TXT" && fi.Extension != ".txt") continue;
                if (fi.Name[0] == 'B' || fi.Name[0] == 'b')
                {
                    st = new SceneFile_Book_of_Shadow(fName);
                    ed = fi.Name.LastIndexOf('.');
                }
                else
                {

                    st = new SceneFile_WQSG(fName);
                    if (ed < 0) ed = fi.Name.LastIndexOf('.');
                }

                String sfName = dName + fi.Name.Substring(0, ed);
                SceneFileByte sf = new SceneFileByte(sfName, cpf);
                sf.Import(st);
                sf.Close();
            }
            MessageBox.Show("导入完成");
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBoxTableFile.Enabled = (comboBox1.SelectedIndex == 0);
        }


    }
}
